import 'package:lighthouse/routes.dart';
import 'index.dart';

void main() => Global.init().then((e) => runApp(const MyApp()));

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    Widget? home;
    if (Global.profile.user != null) {
      if (Global.profile.isInitData == true) {
        home = const StartPage();
      } else {
        home = const InitDataPage();
      }
    } else {
      home = const LoginPage();
    }

    return MultiProvider(
      providers: [
        ChangeNotifierProvider.value(value: ThemeModel()),
        ChangeNotifierProvider.value(value: UserModel()),
        ChangeNotifierProvider.value(value: LocaleModel()),
        ChangeNotifierProvider.value(value: TextScalingModel()),
        ChangeNotifierProvider.value(value: DarkModel()),
        ChangeNotifierProvider.value(value: TimeDilationModel()),
      ],
      child: Consumer3<DarkModel, ThemeModel, LocaleModel>(builder:
          (BuildContext context, darkModel, themeModel, localeModel, child) {
        return MaterialApp(
          themeMode: darkModel.getThemeMode(),
          theme: AppThemeData.lightThemeData,
          darkTheme: AppThemeData.darkThemeData,
          onGenerateTitle: (context) {
            return S.of(context).title;
          },
          home: home,
          locale: localeModel.getLocale(),
          supportedLocales: S.delegate.supportedLocales,
          localizationsDelegates: const [
            S.delegate,
            GlobalMaterialLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate
          ],
          localeResolutionCallback:
              (Locale? locale, Iterable<Locale> supportedLocales) {
            if (localeModel.getLocale() != null) {
              //如果已经选定语言，则不跟随系统
              return localeModel.getLocale();
            } else {
              //跟随系统
              Locale _locale;
              if (supportedLocales.contains(locale)) {
                _locale = locale!;
              } else {
                //如果系统语言不是中文简体或美国英语，则默认使用简体中文
                _locale = const Locale('zh');
              }
              return _locale;
            }
          },
          onGenerateRoute: RouteConfiguration.onGenerateRoute,
          // 注册路由表
          routes: RouteConfiguration.routes,
        );
      }),
    );
  }
}
